import React from 'react'
import { Col, Icon, Row, message } from 'antd'
import NavMenu from './common/nav-menu'
import { connect } from 'react-redux'
import VideoDetailBox from './video-detail-box'
import { withRouter } from 'react-router-dom'
import { getVideo } from '../actions/video'
import ApplicationModal from './common/application-modal'
import { apply } from '../actions/application'

class VideoDetailPage extends React.Component {
  state = {
    isApplicationModalOpen: false,
    reason: ''
  }
  submitApplication = () => {
    const {reason} = this.state
    const {video} = this.props
    this.props.apply({resourceId: video.id, type: 'video', reason}, () => {
      message.success('申请成功')
      this.setState({isApplicationModalOpen: false})
    })
  }
  componentDidMount = () => {
    const {videoId} = this.props.match.params
    this.props.getVideoById(videoId)
  }
  readyPlay = () => {
    const {video} = this.props
    if (video.isNeedSubscribe) {
      message.warning('请先申请订阅')
      this.setState({isApplicationModalOpen:true})
      return
    }
  }

  render () {
    const {video} = this.props
    const {isApplicationModalOpen, reason} = this.state
    return <div>
      <NavMenu/>
      <span style={{float: 'right'}}>
                {
                  video.isNeedSubscribe
                    ? <a onClick={() => this.setState({isApplicationModalOpen: true})}>申请订阅</a>
                    : <span><Icon type="pushpin"/>已订阅</span>
                }
              </span>
      <Row type='flex' justify={'center'}>
        <Col span={16}>
          <VideoDetailBox
            readyPlay={this.readyPlay}
            video={video}/>
        </Col>
      </Row>

      <ApplicationModal
        isApplicationModalOpen={isApplicationModalOpen}
        submitApplication={this.submitApplication}
        closeApplicationModalOpen={() => this.setState({isApplicationModalOpen: false})}
        changeReason={e => this.setState({reason: e.target.value})}
        reason={reason}
      />
    </div>
  }
}

const mapStateToProps = ({video}) => ({
  video
})
const mapDispatchToProps = dispatch => ({
  getVideoById: videoId => dispatch(getVideo(videoId)),
  apply: (application, callback) => dispatch(apply(application, callback))
})
export default withRouter(connect(mapStateToProps, mapDispatchToProps)(VideoDetailPage))
